package com.movie.api.utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

public class ExcelReportUtil {
    public static void generateExcelReport(XSSFWorkbook workbook, Map<String, Object> data, Integer status) {
        XSSFSheet sheet = workbook.getSheetAt(0);
        if (status == 0) { // 状态0表示：近30天数据报表，需要添加期限
            LocalDateTime end = LocalDateTime.now();
            LocalDateTime start = end.minusDays(30);
            sheet.getRow(1).getCell(1).setCellValue("时间：" + start + " 至 " + end);
        }
        @SuppressWarnings("unchecked")
        Map<String, Object> summary = (Map<String, Object>) data.get("summary");
        XSSFRow row = sheet.getRow(3); // 第四行
        row.getCell(2).setCellValue((Long) summary.get("totalViews"));
        row.getCell(4).setCellValue((Long) summary.get("maxViews"));
        row.getCell(6).setCellValue((Long) summary.get("minViews"));
        // 填充数据
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> details = (List<Map<String, Object>>) data.get("details");
        int rowNum = 7;
        for (Map<String, Object> detail : details) {
            row = sheet.getRow(rowNum++);
            row.getCell(1).setCellValue((Integer) detail.get("rank"));
            row.getCell(2).setCellValue((String) detail.get("name"));
            row.getCell(3).setCellValue((String) detail.get("release_time"));
            row.getCell(4).setCellValue((String) detail.get("type"));
            row.getCell(5).setCellValue((String) detail.get("region"));
            row.getCell(6).setCellValue((Integer) detail.get("duration"));
            row.getCell(7).setCellValue((String) detail.get("director"));
            row.getCell(8).setCellValue((Long) detail.get("views"));
        }
    }
}
